package de.wwu.moneyrec;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.util.LinkedList;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

public class CameraManuel extends Activity {

	private Camera camera;
	private Parameters parameters;
	private SurfaceView surfaceView;
	private boolean isPreviewing;
	
	public LinkedList<Money> fives = new LinkedList<Money>();
	public LinkedList<Money> tens = new LinkedList<Money>();
	public LinkedList<Money> twentys = new LinkedList<Money>();
	public LinkedList<Money> fiftys = new LinkedList<Money>();
	public LinkedList<Money> one_hundreds = new LinkedList<Money>();
	public LinkedList<Money> two_hundreds = new LinkedList<Money>();
	public LinkedList<Money> five_hundreds = new LinkedList<Money>();
	
	Bitmap bitmap = null;
	
	
	private FrameLayout frameLayout;
	public TextView textView;
	private ImageOperationDBClusterPrev prevThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		prevThread = new ImageOperationDBClusterPrev(CameraManuel.this, bitmap);
		
		frameLayout = new FrameLayout(this);
		textView = new TextView(this);
		textView.setTextColor(Color.RED);

		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		surfaceView = new SurfaceView(this);
		SurfaceHolder holder = surfaceView.getHolder();
		holder.addCallback(SurfaceViewCallback);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		camera = Camera.open();
		
		parameters = camera.getParameters();
		parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
		parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
		camera.setParameters(parameters);

		camera.startPreview();
		isPreviewing = true;

		setContentView(frameLayout);
		frameLayout.addView(surfaceView);
		frameLayout.addView(textView);
		
		enablePreviewPictures();
		
		loadDB();
		}
	
	private void loadDB(){
    	try {
			InputStream is = this.getAssets().open("imageDBAndroid.imgDB");
			ObjectInputStream inputStream = new ObjectInputStream(is);
			
			LinkedList<LinkedList<Money>> colorDB = new LinkedList<LinkedList<Money>>();
			colorDB = (LinkedList<LinkedList<Money>>) inputStream.readObject();
			
			fives = colorDB.get(0);
			tens = colorDB.get(1);
			twentys = colorDB.get(2);
			fiftys = colorDB.get(3);
			one_hundreds = colorDB.get(4);
			two_hundreds = colorDB.get(5);
			five_hundreds = colorDB.get(6);
			
		} catch (IOException e) {
			Log.e("wichtig", "FEHLER BEIM LEVEL LADEN: " + e.toString());
		} catch (ClassNotFoundException e) {
			Log.e("wichtig", "FEHLER BEIM LEVEL LADEN: " + e.toString());
		}
    }

	private Callback SurfaceViewCallback = new Callback() {
		public void surfaceDestroyed(SurfaceHolder holder) {}

		public void surfaceCreated(SurfaceHolder holder) {}

		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			try {
				camera.setPreviewDisplay(holder);
			} catch (IOException e) {
				Log.e("fehler", e.toString());
			}
		}
	};
	
	private AutoFocusCallback afc = new AutoFocusCallback() {
		public void onAutoFocus(boolean success, Camera camera) {
			if (success && bitmap != null){
				ImageOperationDBClusterPrev prevThread = new ImageOperationDBClusterPrev(CameraManuel.this, bitmap);
				prevThread.run();
			}
		}
	};


	private PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] _data, Camera _camera) {
			Bitmap bitmap = BitmapFactory.decodeByteArray(_data, 0,	_data.length);
		}
	};
	
	private void enablePreviewPictures() {
//		camera.setOneShotPreviewCallback(cb);
		 camera.setPreviewCallback(cb);
	}
	
	private PreviewCallback cb = new PreviewCallback() {

		public void onPreviewFrame(byte[] data, Camera camera) {
			Camera.Parameters parameters = camera.getParameters();
			int format = parameters.getPreviewFormat();

			// Umwandlung zur Bitmap
			if (format == ImageFormat.NV21) {
				int w = parameters.getPreviewSize().width;
				int h = parameters.getPreviewSize().height;
				// Get the YuV image
				YuvImage yuv_image = new YuvImage(data, format, w, h, null);
				// Convert YuV to Jpeg
				Rect rect = new Rect(0, 0, w, h);
				ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
				yuv_image.compressToJpeg(rect, 100, output_stream);
				// Convert from Jpeg to Bitmap
				Bitmap bitmap = BitmapFactory.decodeByteArray(output_stream.toByteArray(), 0, output_stream.size());
				CameraManuel.this.bitmap = bitmap;
				
				if (!prevThread.isAlive()) {
					prevThread.run();
				}
			}
		}
	};

	@Override
	public boolean onTrackballEvent(android.view.MotionEvent event) {
		if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
//			if (isPreviewing) {
//				camera.autoFocus(afc);
//				isPreviewing = false;
//			} else {
//				camera.startPreview();
//				isPreviewing = true;
//			}
			
		}
		return true;
	};

	@Override
	protected void onPause() {
		super.onPause();
		camera.setPreviewCallback(null);
		camera.stopPreview();
		camera.release();
	}
}
